import { JSX } from 'preact'
import { useState } from 'preact/hooks'
import { IEVersion } from '@/utils/index'
import { useInterval } from '@/hooks/useInterval'

const IE8Lte = IEVersion && IEVersion <= 8

function CopIEInput(props: CopInputProps) {
  const { onInput, onFocus, onBlur, ...restProps } = props

  function diffInput(value: string) {
    if (onInput && props.value !== value) {
      onInput(value)
    }
  }

  const [inputEle, setInputEle] = useState<HTMLInputElement | null>(null)
  useInterval(
    () => {
      if (inputEle) {
        diffInput(inputEle.value)
      }
    },
    inputEle ? 50 : null
  )

  return (
    <input
      {...restProps}
      onFocus={(ev) => {
        const ele = ev.target as HTMLInputElement
        setInputEle(ele)
        if (onFocus) {
          ;(onFocus as (ev: FocusEvent) => void)(ev)
        }
      }}
      onBlur={(ev) => {
        if (inputEle) {
          diffInput(inputEle.value)
        }
        setInputEle(null)
        if (onBlur) {
          ;(onBlur as (ev: FocusEvent) => void)(ev)
        }
      }}
    />
  )
}

function CopInInput(props: CopInputProps) {
  const { onInput, ...restProps } = props

  return (
    <input
      {...restProps}
      onInput={(ev) => {
        const { value } = ev.target as HTMLInputElement
        onInput?.(value)
      }}
    />
  )
}

export const CopInput = IE8Lte ? CopIEInput : CopInInput

export interface CopInputProps
  extends Omit<JSX.HTMLAttributes<HTMLInputElement>, 'className' | 'onInput'> {
  value?: string
  onInput?: (value: string) => void
}
